package cn.tedu.recruitmentwebsite.base.handler;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ChatWebSocketHandler extends TextWebSocketHandler {

    private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        String payload = message.getPayload();
        // 假设消息格式为 JSON: { "sender": "user1", "recipient": "user2", "content": "Hello" }
        Map<String, Object> data = parseJson(payload);

        // 检查 recipient 是否存在且不为 null
        if (data.containsKey("recipient")) {
            String recipient = (String) data.get("recipient");

            // 检查 recipient 是否为 null
            if (recipient != null) {
                WebSocketSession recipientSession = sessions.get(recipient);

                if (recipientSession != null && recipientSession.isOpen()) {
                    recipientSession.sendMessage(new TextMessage(payload));
                } else {
                    session.sendMessage(new TextMessage("Recipient not found or not connected"));
                }
            } else {
                session.sendMessage(new TextMessage("Invalid recipient in message"));
            }
        } else {
            session.sendMessage(new TextMessage("Missing recipient in message"));
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 确保 userId 存在且不为 null
        Object userIdObj = session.getAttributes().get("userId");
        if (userIdObj instanceof String) {
            String userId = (String) userIdObj;
            sessions.put(userId, session);
        } else {
            throw new IllegalArgumentException("Invalid or missing userId attribute");
        }
    }


    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String userId = (String) session.getAttributes().get("userId");
        if (userId != null) {
            sessions.remove(userId);
            System.out.println("User " + userId + " disconnected");
        }
    }

    private Map<String, Object> parseJson(String json) {
        // 使用 JSON 解析库（如 Jackson）来解析 JSON 字符串
        // 这里假设你已经添加了 Jackson 依赖
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {});
        } catch (Exception e) {
            e.printStackTrace();
            return Collections.emptyMap();
        }
    }
}
